/*
Copyright (c) 2010 Andreas Bjerkeholt
License: MIT
http://www.opensource.org/licenses/mit-license.php
*/
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include "list.h"

void listInsertLast(list* list, void* data)
{
	list->count++;
	listNode* a = (listNode*)malloc(sizeof(listNode));
	a->data = data;
	a->next = NULL;

	if (list->first == NULL)
	{
		list->first = a;
		return;
	}

	listNode* cur = list->first;
	while (1)
	{
		if (cur->next == NULL)
		{
			cur->next = a;
			break;
		}

		cur = (listNode*)cur->next;
	}
}

bool listDelete(list* list, void* element)
{
	if (list->first == NULL)
		return false;

	listNode* cur = list->first;
	
	if (cur->data == element)
	{
		listNode* temp = cur->next;
		free(cur->data);
		free(cur);

		list->first = temp;
		list->count--;
		return true;
	}

	listNode* next;

	while (1)
	{
		next = cur->next;

		if (next == NULL)
		{
			return false;
		}

		if (next->data == element)
		{
			cur->next = next->next;

			free(next->data);
			free(next);

			list->count--;
			return true;
		}

		cur = next;
	}

	return false;
}

void listDeleteAll(list* list)
{
	if (list->first == NULL)
		return;

	listNode* cur = list->first;
	list->first = NULL;
	while (cur != NULL)
	{
		listNode* temp = cur;
		cur = cur->next;
		free(temp->data);
		free(temp);
	}

	list->count = 0;
}

void listDeleteFirst(list* list)
{
	if (list->first == NULL)
		return;

	listNode* temp = list->first;
	list->first = temp->next;
	free(temp->data);
	free(temp);

	list->count--;
}

void* listGetFirst(list* list)
{
	if (list->first == NULL)
		return NULL;

	listNode* temp = list->first;
	return temp->data;
}
